const CartModel = require('../models/cart.model');
const { ValidationError } = require('../middleware/error');

class CartController {
  // 获取购物车内容
  static async getCart(req, res, next) {
    try {
      const userId = req.user.id;
      const cart = await CartModel.getCart(userId);
      
      res.json({
        data: cart.items,
        meta: cart.summary
      });
    } catch (error) {
      next(error);
    }
  }

  // 添加商品到购物车
  static async addItem(req, res, next) {
    try {
      const userId = req.user.id;
      const { product_id, quantity = 1 } = req.body;

      // 验证输入
      if (!product_id) {
        throw new ValidationError('参数错误', {
          product_id: ['商品ID不能为空']
        });
      }

      const quantityNum = parseInt(quantity);
      if (isNaN(quantityNum) || quantityNum < 1) {
        throw new ValidationError('参数错误', {
          quantity: ['数量必须是大于0的整数']
        });
      }

      const cartItem = await CartModel.addItem(userId, product_id, quantityNum);
      
      res.status(201).json({
        data: cartItem,
        message: '商品已添加到购物车'
      });
    } catch (error) {
      next(error);
    }
  }

  // 更新购物车商品数量
  static async updateItemQuantity(req, res, next) {
    try {
      const userId = req.user.id;
      const { cart_item_id } = req.params;
      const { quantity } = req.body;

      // 验证输入
      const quantityNum = parseInt(quantity);
      if (isNaN(quantityNum) || quantityNum < 1) {
        throw new ValidationError('参数错误', {
          quantity: ['数量必须是大于0的整数']
        });
      }

      const cartItem = await CartModel.updateItemQuantity(userId, cart_item_id, quantityNum);
      
      res.json({
        data: cartItem,
        message: '购物车商品数量已更新'
      });
    } catch (error) {
      next(error);
    }
  }

  // 从购物车中移除商品
  static async removeItem(req, res, next) {
    try {
      const userId = req.user.id;
      const { cart_item_id } = req.params;

      await CartModel.removeItem(userId, cart_item_id);
      
      res.json({
        message: '商品已从购物车中移除'
      });
    } catch (error) {
      next(error);
    }
  }

  // 清空购物车
  static async clear(req, res, next) {
    try {
      const userId = req.user.id;
      await CartModel.clear(userId);
      
      res.json({
        message: '购物车已清空'
      });
    } catch (error) {
      next(error);
    }
  }

  // 验证购物车
  static async validateCart(req, res, next) {
    try {
      const userId = req.user.id;
      const validation = await CartModel.validateItems(userId);
      
      res.json({
        data: validation
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = CartController; 